package com.lzb.browser.fragment;

import android.Manifest;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;

import java.io.File;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.graphics.Color;
import android.widget.Toast;
import android.widget.EditText;
import android.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.inputmethod.InputMethodManager;
import android.view.KeyEvent;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lzb.browser.BaseNoModelFragment;
import com.lzb.browser.HomeActivity;
import com.lzb.browser.R;
import com.lzb.browser.bean.CollectBean;
import com.lzb.browser.bean.RecordBean;
import com.lzb.browser.databinding.FragmentBrowswerBinding;
import com.lzb.browser.dialog.AddCollectDialog;
import com.lzb.browser.utils.AppSpUtils;
import com.lzb.browser.utils.IconUtils;
import com.lzb.browser.basic.utils.SPUtil;
import com.lzb.browser.Content;

import java.util.ArrayList;
import java.util.List;

/**
 * WebView Fragment - 浏览器加载页面
 */
public class BrowserFragment extends BaseNoModelFragment<FragmentBrowswerBinding> {

    private static final String ARG_URL = "url";
    private String currentUrl;

    private int findIndex = 0; // 当前查找位置
    private int findTotal = 0; // 总匹配数

    /**
     * 创建WebViewFragment实例
     *
     * @param url 要加载的URL
     * @return WebViewFragment实例
     */
    public static BrowserFragment newInstance(String url) {
        BrowserFragment fragment = new BrowserFragment();
        Bundle args = new Bundle();
        args.putString(ARG_URL, url);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int onCreate() {
        return com.lzb.browser.R.layout.fragment_browswer;
    }

    @Override
    protected void initView() {
        // 获取传递的URL参数
        if (getArguments() != null) {
            currentUrl = getArguments().getString(ARG_URL);
        }

        // 初始化WebView设置
        setupWebView();

        // 加载URL
        if (currentUrl != null && !currentUrl.isEmpty()) {
            loadUrl(currentUrl);
        }
    }

    @Override
    protected void initData() {
        // 数据初始化
    }

    /**
     * 初始化WebView设置
     */
    private void setupWebView() {
        WebSettings webSettings = mDataBinding.webView.getSettings();

        // 启用JavaScript
        webSettings.setJavaScriptEnabled(true);

        // 设置缓存模式
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);

        // 支持缩放
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);

        // 自适应屏幕
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);

        // 启用DOM存储，确保JavaScript能正常操作DOM
        webSettings.setDomStorageEnabled(true);

        // 启用Cookie支持
        CookieManager cookieManager = CookieManager.getInstance();
        boolean isTracelessMode = SPUtil.getBoolean(getActivity(), Content.isTracelessMode, false);

        if (isTracelessMode) {
            // 无痕模式下禁用Cookie
            cookieManager.setAcceptCookie(false);
            cookieManager.setAcceptThirdPartyCookies(mDataBinding.webView, false);
        } else {
            // 正常模式下启用Cookie
            cookieManager.setAcceptCookie(true);
            cookieManager.setAcceptThirdPartyCookies(mDataBinding.webView, true); // 支持第三方Cookie
        }

        // 设置无痕模式
        updateTracelessMode();

        // 设置无图模式
        updateImagelessMode();

        //浏览器UA标识
        String uaCode = SPUtil.getString(mContext, Content.browseIdentification, "");
        if (!TextUtils.isEmpty(uaCode)) {
            mDataBinding.webView.getSettings().setUserAgentString(uaCode);
        }

        // 设置WebViewClient
        mDataBinding.webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();

                // 处理首次加载时的URL协议问题
                if (url.startsWith("http://") || url.startsWith("https://")) {
                    return false; // 标准HTTP/HTTPS协议，在WebView中加载
                } else if (url.startsWith("file://") || url.startsWith("content://")) {
                    return false; // 文件或内容协议，在WebView中加载
                } else {
                    // 非标准协议（如intent://, market://等），尝试外部处理
//                    try {
//                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        startActivity(intent);
                    return true; // 已处理，不加载
//                    } catch (Exception e) {
//                        // 无法处理，继续在WebView中尝试加载
//                        return false;
//                    }
                }
            }

            @Override
            public void onPageStarted(WebView view, String url, android.graphics.Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
//                showDialog("加载中...");

                // 在页面开始加载时注入夜间模式CSS
                boolean isNightMode = SPUtil.getBoolean(getActivity(), Content.isNightMode, false);
                if (isNightMode) {
                    injectNightModeCSS();
                    // 延迟再次注入，确保页面结构建立
                    view.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            injectNightModeCSS();
                        }
                    }, 200);
                }

                // 在页面加载时应用无图模式设置
                updateImagelessMode();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//                hideDialog();
                // 页面加载完成后通知宿主Activity更新导航按钮状态
                if (getActivity() instanceof HomeActivity) {
                    ((HomeActivity) getActivity()).updateNavigationButtonsState();
                }
                saveRecord();
            }
        });

        // 设置WebChromeClient
        mDataBinding.webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                mDataBinding.progressBar.setProgress(newProgress);
                if (newProgress == 100) {
                    mDataBinding.progressBar.setVisibility(View.GONE);
                } else {
                    mDataBinding.progressBar.setVisibility(View.VISIBLE);
                }
            }
        });

        // 设置长按图片下载功能
        setupLongClickListener();

        // 设置下载监听器
        mDataBinding.webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                // 根据文件类型选择下载方式
                if (mimetype != null && mimetype.startsWith("image/")) {
                    // 图片文件使用图片下载方式（带对话框）
                    downloadImage(url, userAgent, contentDisposition, mimetype);
                } else {
                    // 其他文件使用普通下载方式
                    downloadFile(url, userAgent, contentDisposition, mimetype);
                }
            }
        });
    }

    /**
     * 加载URL
     *
     * @param url 要加载的URL
     */
    public void loadUrl(String url) {
        if (mDataBinding.webView != null && !TextUtils.isEmpty(url)) {
            mDataBinding.webView.loadUrl(url);
            currentUrl = url;

            // 检查夜间模式，在页面加载过程中注入CSS
            if (SPUtil.getBoolean(getActivity(), Content.isNightMode, false)) {
                // 立即尝试注入CSS
                injectNightModeCSS();
                // 延迟再次注入，确保页面结构已建立
                mDataBinding.webView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        injectNightModeCSS();
                    }
                }, 100);
            }
        }
    }

    /**
     * 获取当前加载的URL
     *
     * @return 当前URL
     */
    public String getCurrentUrl() {
        return currentUrl;
    }

    /**
     * 是否可以后退
     *
     * @return true表示可以后退
     */
    public boolean canGoBack() {
        return mDataBinding.webView != null && mDataBinding.webView.canGoBack();
    }

    /**
     * 后退
     */
    public void goBack() {
        if (mDataBinding.webView != null && mDataBinding.webView.canGoBack()) {
            mDataBinding.webView.goBack();
            // 延迟更新状态，等待WebView状态变化完成
            mDataBinding.webView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (getActivity() instanceof HomeActivity) {
                        ((HomeActivity) getActivity()).updateNavigationButtonsState();
                    }
                }
            }, 100);
        }
    }

    /**
     * 是否可以前进
     *
     * @return true表示可以前进
     */
    public boolean canGoForward() {
        return mDataBinding.webView != null && mDataBinding.webView.canGoForward();
    }

    /**
     * 前进
     */
    public void goForward() {
        if (mDataBinding.webView != null && mDataBinding.webView.canGoForward()) {
            mDataBinding.webView.goForward();
            // 延迟更新状态，等待WebView状态变化完成
            mDataBinding.webView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (getActivity() instanceof HomeActivity) {
                        ((HomeActivity) getActivity()).updateNavigationButtonsState();
                    }
                }
            }, 100);
        }
    }

    /**
     * 重新加载页面
     */
    public void reload() {
        if (mDataBinding.webView != null) {
            mDataBinding.webView.reload();
        }
    }

    /**
     * 更新无图模式设置
     */
    public void updateImagelessMode() {
        boolean isImagelessMode = SPUtil.getBoolean(getActivity(), Content.isImagelessMode, false);
        if (mDataBinding.webView != null && mDataBinding.webView.getSettings() != null) {
            mDataBinding.webView.getSettings().setBlockNetworkImage(isImagelessMode);
            mDataBinding.webView.getSettings().setLoadsImagesAutomatically(!isImagelessMode);
        }
    }

    /**
     * 更新无痕模式设置
     */
    public void updateTracelessMode() {
        boolean isTracelessMode = SPUtil.getBoolean(getActivity(), Content.isTracelessMode, false);
        if (mDataBinding.webView != null && mDataBinding.webView.getSettings() != null) {
            WebSettings settings = mDataBinding.webView.getSettings();

            // 无痕模式设置
            if (isTracelessMode) {
                // 禁用缓存
                settings.setCacheMode(WebSettings.LOAD_NO_CACHE);

                // 禁用表单数据保存
                settings.setSaveFormData(false);
                settings.setSavePassword(false);

                // 禁用文件访问
                settings.setAllowFileAccess(false);
                settings.setAllowFileAccessFromFileURLs(false);
                settings.setAllowUniversalAccessFromFileURLs(false);

                // 禁用地理定位
                settings.setGeolocationEnabled(false);

                // 禁用数据库存储
                settings.setDatabaseEnabled(false);
                settings.setDomStorageEnabled(false);
            } else {
                // 正常模式下的设置
                settings.setCacheMode(WebSettings.LOAD_DEFAULT);
                settings.setSaveFormData(true);
                settings.setAllowFileAccess(true);
                settings.setGeolocationEnabled(true);
                settings.setDatabaseEnabled(true);
                settings.setDomStorageEnabled(true);
            }
        }
    }

    /**
     * 获取当前页面的标题
     */
    public String getTitle() {
        if (mDataBinding.webView != null) {
            return mDataBinding.webView.getTitle();
        }
        return null;
    }

    /**
     * 获取当前页面的URL
     */
    public String getUrl() {
        if (mDataBinding.webView != null) {
            return mDataBinding.webView.getUrl();
        }
        return null;
    }

    /**
     * 获取当前页面的图标
     */
    public Bitmap getIcon() {
        if (mDataBinding.webView != null) {
            return mDataBinding.webView.getFavicon();
        }
        return null;
    }

    /**
     * 保存历史记录
     */
    private void saveRecord() {
        // 检查是否开启无痕模式，如果开启则不保存历史记录
        boolean isTracelessMode = SPUtil.getBoolean(getActivity(), Content.isTracelessMode, false);
        if (isTracelessMode) {
            return; // 无痕模式下不保存历史记录
        }

        String title = mDataBinding.webView.getTitle();
        String url = mDataBinding.webView.getUrl();
        if (title != null && url != null) {
            // 获取网站图标URL
            Bitmap icon = mDataBinding.webView.getFavicon();

            // 创建收藏对象
            RecordBean recordBean = new RecordBean(title, url, icon);

            // 获取现有的历史记录
            List<RecordBean> recordList = AppSpUtils.getRecordList();
            if (recordList == null) {
                recordList = new ArrayList<>();
            }

            // 添加到列表
            recordList.add(0, recordBean);

            // 保存到SharedPreferences
            AppSpUtils.saveRecordList(recordList);
        } else {
            ToastUtils.showShort("无法获取页面信息");
        }
    }

    /**
     * 设置长按图片下载监听器
     */
    private void setupLongClickListener() {
        mDataBinding.webView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                WebView.HitTestResult result = mDataBinding.webView.getHitTestResult();
                if (result != null) {
                    int type = result.getType();
                    if (type == WebView.HitTestResult.IMAGE_TYPE ||
                            type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                        String imageUrl = result.getExtra();
                        if (imageUrl != null && !imageUrl.isEmpty()) {
                            // 获取WebView的用户代理
                            String userAgent = mDataBinding.webView.getSettings().getUserAgentString();
                            showDownloadImageDialog(imageUrl, userAgent);
                            return true;
                        }
                    }
                }
                return false;
            }
        });
    }

    /**
     * 显示下载图片对话框
     */
    private void showDownloadImageDialog(final String imageUrl, final String userAgent) {
        new android.app.AlertDialog.Builder(getContext())
                .setTitle("下载图片")
                .setMessage("是否下载这张图片？")
                .setPositiveButton("下载", (dialog, which) -> {
                    // 根据图片URL后缀推断MIME类型
                    String mimetype = null;
                    if (imageUrl.toLowerCase().endsWith(".jpg") || imageUrl.toLowerCase().endsWith(".jpeg")) {
                        mimetype = "image/jpeg";
                    } else if (imageUrl.toLowerCase().endsWith(".png")) {
                        mimetype = "image/png";
                    } else if (imageUrl.toLowerCase().endsWith(".gif")) {
                        mimetype = "image/gif";
                    } else if (imageUrl.toLowerCase().endsWith(".webp")) {
                        mimetype = "image/webp";
                    } else if (imageUrl.toLowerCase().endsWith(".bmp")) {
                        mimetype = "image/bmp";
                    } else {
                        // 默认图片类型
                        mimetype = "image/jpeg";
                    }
                    downloadImage(imageUrl, userAgent, null, mimetype);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 下载普通文件
     *
     * @param url                文件URL
     * @param userAgent          用户代理
     * @param contentDisposition 内容描述
     * @param mimetype           MIME类型
     */
    private void downloadFile(String url, String userAgent, String contentDisposition, String mimetype) {
        try {
            DownloadManager downloadManager = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

            // 设置用户代理
            if (userAgent != null) {
                request.addRequestHeader("User-Agent", userAgent);
            }

            // 解析文件名
            String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);

            // 设置下载路径和文件名 - 使用应用私有目录，无需权限
            String downloadPath = PathUtils.getFilesPathExternalFirst() + Content.download;
            File downloadDir = new File(downloadPath);
            if (!downloadDir.exists()) {
                downloadDir.mkdirs();
            }
            File downloadFile = new File(downloadDir, fileName);
            request.setDestinationUri(Uri.fromFile(downloadFile));

            // 设置通知
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setTitle(fileName);
            request.setDescription(url);

            // 允许在移动网络下下载
            request.setAllowedOverMetered(true);

            // 开始下载
            downloadManager.enqueue(request);

            Toast.makeText(getContext(), "文件下载已开始", Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "文件下载失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 下载图片
     *
     * @param url                图片URL
     * @param userAgent          用户代理
     * @param contentDisposition 内容描述
     * @param mimetype           MIME类型
     */
    private void downloadImage(String url, String userAgent, String contentDisposition, String mimetype) {
        // 检查权限
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 请求权限
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return;
        }

        try {
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

            // 设置User-Agent
            if (userAgent != null) {
                request.addRequestHeader("User-Agent", userAgent);
            }

            // 设置通知栏显示
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            // 设置下载路径和文件名
            String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
            String downloadPath = PathUtils.getFilesPathExternalFirst() + Content.downloadPicture;
            File downloadDir = new File(downloadPath);
            if (!downloadDir.exists()) {
                downloadDir.mkdirs();
            }
            File downloadFile = new File(downloadDir, fileName);
            request.setDestinationUri(Uri.fromFile(downloadFile));

            // 设置标题和描述 - 使用真实文件名而不是固定标题
            request.setTitle(fileName);
            request.setDescription(url);

            // 允许漫游网络下载
            request.setAllowedOverRoaming(true);

            // 获取DownloadManager并执行下载
            DownloadManager downloadManager = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);
            long downloadId = downloadManager.enqueue(request);

            Toast.makeText(getContext(), "图片下载已开始", Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "下载失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 清理WebView
        if (mDataBinding.webView != null) {
            mDataBinding.webView.stopLoading();
            mDataBinding.webView.destroy();
        }
    }

    /**
     * 清除所有Cookie
     */
    public void clearCookies() {
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookies(null);
        cookieManager.flush();
    }

    /**
     * 获取当前URL的Cookie
     */
    public String getCookies(String url) {
        CookieManager cookieManager = CookieManager.getInstance();
        return cookieManager.getCookie(url);
    }

    /**
     * 设置WebView背景颜色
     */
    public void setWebViewBackgroundColor(int color) {
        if (mDataBinding.webView != null) {
            mDataBinding.webView.setBackgroundColor(color);

            // 如果是黑色背景，注入CSS来修改网页背景
            if (color == Color.BLACK) {
                // 立即注入CSS，如果页面已加载完成则直接应用
                injectNightModeCSS();
                // 如果页面还在加载中，延迟再次注入确保样式应用
                mDataBinding.webView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        injectNightModeCSS();
                    }
                }, 100);
            } else {
                removeNightModeCSS();
            }
        }
    }

    /**
     * 注入夜间模式CSS
     */
    private void injectNightModeCSS() {
        if (mDataBinding.webView != null) {
            String css = "html, body { background-color: #000000 !important; color: #ffffff !important; } " +
                    "* { background-color: transparent !important; } " +
                    "div, p, span, h1, h2, h3, h4, h5, h6, article, section, nav, main, aside, header, footer { background-color: #000000 !important; color: #ffffff !important; } " +
                    "a { color: #4a9eff !important; } " +
                    "input, textarea, select { background-color: #1a1a1a !important; color: #ffffff !important; border-color: #333333 !important; }";

            String js = "(function() { " +
                    "var existingStyle = document.getElementById('night-mode-style'); " +
                    "if (existingStyle) { existingStyle.remove(); } " +
                    "var style = document.createElement('style'); " +
                    "style.type = 'text/css'; " +
                    "style.id = 'night-mode-style'; " +
                    "style.innerHTML = '" + css + "'; " +
                    "if (document.head) { document.head.appendChild(style); } " +
                    "else if (document.documentElement) { document.documentElement.appendChild(style); } " +
                    "})();";

            mDataBinding.webView.evaluateJavascript(js, null);
        }
    }

    /**
     * 清除浏览器状态
     */
    public void changeUaCode() {
        if (mDataBinding.webView != null) {
            //浏览器UA标识
            String uaCode = SPUtil.getString(mContext, Content.browseIdentification, "");
            if (!TextUtils.isEmpty(uaCode)) {
                mDataBinding.webView.getSettings().setUserAgentString(uaCode);
                mDataBinding.webView.reload();
            }
        }
    }

    /**
     * 移除夜间模式CSS
     */
    private void removeNightModeCSS() {
        if (mDataBinding.webView != null) {
            String js = "(function() { " +
                    "var style = document.getElementById('night-mode-style'); " +
                    "if (style) { style.remove(); } " +
                    "})();";

            mDataBinding.webView.evaluateJavascript(js, null);
        }
    }

    /**
     * 显示页内查找界面
     */
    public void showFindDialog() {
        // 显示查找布局
        mDataBinding.llFindInPage.setVisibility(View.VISIBLE);

        // 清空输入框
        mDataBinding.etFind.setText("");
        mDataBinding.etFind.requestFocus();

        // 弹出软键盘
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mDataBinding.etFind, InputMethodManager.SHOW_IMPLICIT);

        // 设置查找监听器
        setupFindListeners();
    }

    /**
     * 设置查找相关监听器
     */
    private void setupFindListeners() {
        // 取消按钮点击事件
        mDataBinding.tvCancel.setOnClickListener(v -> {
            hideFindInPage();
        });

        // 上一个按钮点击事件
        mDataBinding.ivLast.setOnClickListener(v -> {
            if (findTotal > 0) {
                mDataBinding.webView.findNext(false);
            }
        });

        // 下一个按钮点击事件
        mDataBinding.ivNext.setOnClickListener(v -> {
            if (findTotal > 0) {
                mDataBinding.webView.findNext(true);
            }
        });

        // 输入框文本变化监听器
        mDataBinding.etFind.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String searchText = s.toString().trim();
                if (!searchText.isEmpty()) {
                    mDataBinding.webView.findAllAsync(searchText);
                } else {
                    mDataBinding.webView.clearMatches();
                    findIndex = 0;
                    findTotal = 0;
                    updateFindResultDisplay();
                }
            }
        });

        // 输入框键盘事件监听器
        mDataBinding.etFind.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                if (findTotal > 0) {
                    mDataBinding.webView.findNext(true);
                }
                return true;
            }
            return false;
        });

        // WebView查找结果监听器
        mDataBinding.webView.setFindListener(new WebView.FindListener() {
            @Override
            public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
                if (isDoneCounting) {
                    findIndex = activeMatchOrdinal + 1; // WebView返回的是0-based索引
                    findTotal = numberOfMatches;
                    updateFindResultDisplay();
                }
            }
        });
    }

    /**
     * 更新查找结果显示
     */
    private void updateFindResultDisplay() {
        if (findTotal > 0) {
            mDataBinding.tvNum.setText(findIndex + "/" + findTotal);
        } else {
            mDataBinding.tvNum.setText("0/0");
        }
    }

    /**
     * 隐藏页内查找界面
     */
    private void hideFindInPage() {
        mDataBinding.llFindInPage.setVisibility(View.GONE);
        mDataBinding.webView.clearMatches();

        // 隐藏软键盘
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mDataBinding.etFind.getWindowToken(), 0);

        // 重置查找状态
        findIndex = 0;
        findTotal = 0;
        updateFindResultDisplay();
    }
}